package com.moyangfenghun.javabase.common;


import com.fasterxml.jackson.annotation.JsonView;
import com.moyangfenghun.javabase.bean.vo.SysUserView;
import lombok.Data;

import java.io.Serializable;

/**
 * @author 江南烟雨时
 * @date 2020/12/3 15:18
 * @description
 */
@Data
@JsonView(SysUserView.Api.class)
public class ApiResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer code;
    private String msg;
    private T data;

    public ApiResult(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ApiResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }

    public ApiResult() {
        this.code = null;
        this.msg = null;
        this.data = null;
    }

    /**
     * 常用成功返回
     *
     * @return
     */
    public static ApiResult ok() {
        return new ApiResult(ApiCode.SUCCESS, "操作成功");
    }

    /**
     * 常用成功带返回信息
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ApiResult<T> ok(T data) {
        return new ApiResult(ApiCode.SUCCESS, "操作成功", data);
    }

    /**
     * 常用失败返回
     *
     * @return
     */
    public static ApiResult fail() {
        return new ApiResult(ApiCode.FAIL, "操作失败");
    }

    /**
     * 常用失败带返回信息
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ApiResult<T> fail(T data) {
        return new ApiResult(ApiCode.FAIL, "操作失败", data);
    }

    /**
     * 自定义返回
     *
     * @param code
     * @param msg
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ApiResult<T> result(Integer code, String msg, T data) {
        return new ApiResult(code, msg, data);
    }

    /**
     * 传入flag判断返回ok还是fail
     *
     * @param flag
     * @return
     */
    public static ApiResult<Boolean> result(boolean flag) {
        if (flag) {
            return ok();
        }
        return fail();
    }
}
